package com.caiyi.financial.nirvana.sms.queue;

import com.alibaba.fastjson.JSON;
import com.caiyi.financial.nirvana.sms.entity.SmsBatchMsg;
import com.caiyi.financial.nirvana.sms.jedis.JedisKey;
import com.caiyi.financial.nirvana.sms.service.SmsBatchMsgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 批次入库
 */
@Component
public class InsertBatchMessageQueue implements IRedisQueue {

    private static final int MAX_CACHE_SIZE = 1000;
    private static final int INSERT_INTERVAL = 3 * 1000;
    private final List<SmsBatchMsg> smsBatchMsgCache = new ArrayList<>();
    private long startTime = System.currentTimeMillis();

    @Autowired
    private SmsBatchMsgService smsBatchMsgService;

    @Override
    public String key() {
        return JedisKey.SMS_QUEUE_BATCH_MSG_DB;
    }

    public void run(List<String> list) {
        if (list != null && !list.isEmpty()) {
            SendQueueEntity entity = JSON.parseObject(list.get(1), SendQueueEntity.class);
            SmsBatchMsg smsBatchMsg = new SmsBatchMsg();
            smsBatchMsg.setBatchId(entity.getBatchId());
            smsBatchMsg.setAccount(entity.getAccount());
            smsBatchMsg.setPhoneCount(entity.getPhoneCount());
            smsBatchMsg.setPhones(entity.getPhone());
            smsBatchMsg.setContent(entity.getContent());
            smsBatchMsg.setIp(entity.getIp());
            smsBatchMsg.setNotifyUrl(entity.getNotifyUrl());
            smsBatchMsg.setUid(entity.getUid());
            smsBatchMsg.setCreateTime(new Date());
            smsBatchMsg.setUpdateTime(new Date());
            smsBatchMsgCache.add(smsBatchMsg);
        }
        boolean batch = this.smsBatchMsgCache.size() == MAX_CACHE_SIZE || (System.currentTimeMillis() - startTime) > INSERT_INTERVAL;
        batch = batch && smsBatchMsgCache.size() > 0;
        if (batch) {
            //开始插入
            this.smsBatchMsgService.insertList(smsBatchMsgCache);
            //清空缓存
            smsBatchMsgCache.clear();
            //重置时间
            startTime = System.currentTimeMillis();
        }
    }

    @Override
    public void interrupt(Exception e) {

    }
}
